package com.android.lovely.framework

import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewbinding.ViewBinding
import com.android.lovely.R
import com.android.lovely.databinding.FragmentHomeListBinding
import com.android.lovely.ext.init
import com.android.lovely.framework.widget.FlexibleContentContainer
import kotlinx.coroutines.flow.collectLatest

/**
 *
 * @author why
 * @date 2025/3/11 15:48
 */
abstract class BaseLoadFragment<
        DB : ViewBinding,
        T : Any,> :
    BaseFragment<DB>() {

    val adapter: BaseLoadAdapter<T, *> by lazy { getBaseAdapter() }

    abstract fun getViewModel(): BaseLoadViewModel<T>
    override fun initView() {

        getRecyclerView().adapter = adapter.buildAdapter()
        getSwipeRefreshLayout().init()
        getSwipeRefreshLayout().setOnRefreshListener {
            adapter.refresh()
        }
        getStateLayout().setLoadState(adapter)
        setNoContent()
        getStateLayout().setNoContentClickListener { adapter.refresh() }
        viewLifecycleOwner.lifecycleScope.launchWhenResumed {
            getViewModel().pager.collectLatest { it ->
                adapter.submitData(it)
            }
        }
        adapter.addOnPagesUpdatedListener {
            getSwipeRefreshLayout().isRefreshing = false
            if (getViewModel().currentPage == 1) {
                getRecyclerView().scrollToPosition(0)
            }
        }
    }


    abstract fun getStateLayout(): FlexibleContentContainer
    abstract fun getSwipeRefreshLayout(): SwipeRefreshLayout
    abstract fun getRecyclerView(): RecyclerView
    abstract fun getBaseAdapter(): BaseLoadAdapter<T, *>

    open fun setNoContent() {
        getStateLayout().setNoContentIcon(R.drawable.icon_no_content)
        getStateLayout().setNoContentText(getString(R.string.no_content))
        getStateLayout().setNoContentButton(getString(R.string.refresh), true) {
            adapter.refresh()
        }
    }
}